use crate::utils::templates;
use anyhow::Result;
use colored::*;
use std::fs;
use std::path::Path;

pub async fn run(name: String, framework: String, output_dir: String) -> Result<()> {
    println!("{} {} component", "🧩 Generating".cyan(), name);

    let component_dir = Path::new(&output_dir).join(&name);
    fs::create_dir_all(&component_dir)?;

    match framework.as_str() {
        "react" => generate_react_component(&name, &component_dir)?,
        "vue" => generate_vue_component(&name, &component_dir)?,
        _ => return Err(anyhow::anyhow!("Unsupported framework: {}", framework)),
    }

    println!(
        "{} {} component in {}",
        "✅ Generated".green(),
        name,
        component_dir.display()
    );
    Ok(())
}

fn generate_react_component(name: &str, dir: &Path) -> Result<()> {
    let component_content = templates::react_component(name);
    let style_content = templates::component_styles(name);
    let test_content = templates::react_test(name);

    fs::write(dir.join(format!("{}.tsx", name)), component_content)?;
    fs::write(dir.join(format!("{}.module.css", name)), style_content)?;
    fs::write(dir.join(format!("{}.test.tsx", name)), test_content)?;

    Ok(())
}

fn generate_vue_component(name: &str, dir: &Path) -> Result<()> {
    let component_content = templates::vue_component(name);

    fs::write(dir.join(format!("{}.vue", name)), component_content)?;

    Ok(())
}
